# encoding: utf-8
from flask import Blueprint, views, render_template, session, redirect, url_for, request, g
from .models import CMSUser, CMSPermission, CMSRole
from ..models import BannerModel, BoardModel, HighlightPostModel, PostModel
from ..front.models import FrontUser
from .forms import LoginForm, ResetForm, ResetEmailForm, AddBannerForm, UpdateBannerForm, AddBoardForm, UpdateBoardForm, \
    AddCuserForm, C_FoundPwdForm
from .decorators import login_required, permission_requred
from flask_paginate import Pagination, get_page_parameter
import config
from exts import db
from utils import restful

bp = Blueprint('cms', __name__, url_prefix='/cms')


@bp.route('/')
@login_required
def index():
    return render_template('cms/cms_index.html')


# 帖子
@bp.route('/posts/')
@login_required
@permission_requred(CMSPermission.POSTER)
def posts():
    page = request.args.get(get_page_parameter(), type=int, default=1)
    start = (page - 1) * config.PER_PAGE
    end = start + config.PER_PAGE
    posts = db.session.query(PostModel).outerjoin(HighlightPostModel).order_by(HighlightPostModel.create_time.desc(),
                                                                               PostModel.create_time.desc()).slice(
        start, end)
    total = PostModel.query.count()
    pagination = Pagination(bs_version=3, page=page, total=total)
    content = {
        'posts': posts,
        'pagination': pagination
    }
    return render_template('cms/cms_posts.html', **content)


@bp.route('/hpost/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.POSTER)
def hpost():
    post_id = request.form.get('post_id')
    if not post_id:
        return restful.params_error('请传入帖子id！')
    post = PostModel.query.get(post_id)
    if not post:
        return restful.params_error('没有这个帖子！')
    highlight = HighlightPostModel()
    highlight.post = post
    db.session.add(highlight)
    db.session.commit()
    return restful.success()


@bp.route('/uhpost/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.POSTER)
def uhpost():
    post_id = request.form.get('post_id')
    if not post_id:
        return restful.params_error('请传入帖子id！')
    post = PostModel.query.get(post_id)
    if not post:
        return restful.params_error('没有这个帖子！')
    highlight = HighlightPostModel.query.filter_by(post_id=post_id).first()
    db.session.delete(highlight)
    db.session.commit()
    return restful.success()


# 封贴
@bp.route('/banned/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.POSTER)
def banned():
    post_id = request.form.get('post_id')
    if not post_id:
        return restful.params_error('请传入帖子id！')
    post = PostModel.query.get(post_id)
    if not post:
        return restful.params_error('没有这个帖子！')
    # 帖子状态改为0，意味被封了！
    if post.is_banned == 1:
        post.is_banned = 0
        db.session.commit()
    return restful.success()


# 帖子解封
@bp.route('/unbanned/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.POSTER)
def unbanned():
    post_id = request.form.get('post_id')
    if not post_id:
        return restful.params_error('请传入帖子id！')
    post = PostModel.query.get(post_id)
    if not post:
        return restful.params_error('没有这个帖子！')
        # 帖子状态改为0，意味解封了！
    if post.is_banned == 0:
        post.is_banned = 1
        db.session.commit()
    return restful.success()


# 评论
@bp.route('/comments/')
@login_required
@permission_requred(CMSPermission.COMMENTER)
def comments():
    return render_template('cms/cms_comments.html')


# 板块
@bp.route('/boards/')
@login_required
@permission_requred(CMSPermission.BOARDER)
def boards():
    board_model = BoardModel.query.order_by(BoardModel.create_time.desc()).all()
    content = {
        'boards': board_model
    }
    return render_template('cms/cms_boards.html', **content)


# 添加板块
@bp.route('/aboard/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.BOARDER)
def aboard():
    form = AddBoardForm(request.form)
    if form.validate():
        name = form.name.data
        desc = form.desc.data
        board = BoardModel(name=name, desc=desc)
        db.session.add(board)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(form.get_error())


# 修改板块
@bp.route('/uboard/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.BOARDER)
def uboard():
    form = UpdateBoardForm(request.form)
    if form.validate():
        name = form.name.data
        desc = form.desc.data
        board_id = form.board_id.data
        board = BoardModel.query.get(board_id)
        if board:
            board.name = name
            board.desc = desc
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error('板块不存在！')
    else:
        return restful.params_error(form.get_error())


# 删除
@bp.route('/dboard/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.BOARDER)
def dboard():
    board_id = request.form.get('board_id')
    if not board_id:
        return restful.params_error('请传入板块的id！')
    board = BoardModel.query.get(board_id)
    if not board:
        return restful.params_error('板块不存在！')
    db.session.delete(board)
    db.session.commit()
    return restful.success()


# 前台用户
@bp.route('/fusers/')
@login_required
@permission_requred(CMSPermission.FRONTUSER)
def fusers():
    fusers = FrontUser.query.all()
    content = {
        'fusers': fusers
    }
    return render_template('cms/cms_fusers.html', **content)


# 后台管理人员cms用户
@bp.route('/cusers/')
@login_required
@permission_requred(CMSPermission.CMSUSER)
def cusers():
    cusers = CMSUser.query.all()
    roles = CMSRole.query.all()
    content = {
        'roles': roles,
        'cusers': cusers
    }
    return render_template('cms/cms_cusers.html', **content)


# 添加cms用户
@bp.route('/acuser/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.CMSUSER)
def acuser():
    form = AddCuserForm(request.form)
    if form.validate():
        username = form.username.data
        emial = form.email.data
        password = form.password.data
        role_id = form.role_id.data
        role = CMSRole.query.get(role_id)
        if role:
            user = CMSUser(username=username, password=password, email=emial)
            user.roles.append(role)
            db.session.add(user)
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error('系统中没有这个权限！')
    else:
        return restful.params_error(form.get_error())


# 修改权限
@bp.route('/updateAuth/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.CMSUSER)
def updateAuth():
    cuser_id = request.form.get('cuser_id')
    name = request.form.get('name')
    cuser = CMSUser.query.get(cuser_id)
    role = CMSRole.query.filter_by(name=name).first()
    if not role:
        return restful.params_error('系统中没有这个权限！')
    cuser.roles[0] = role
    db.session.add(cuser)
    db.session.commit()

    return restful.success()


# cms移入黑名单
@bp.route('/inblacklist/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.CMSUSER)
def inblacklist():
    cuser_id = request.form.get('cuser_id')
    if not cuser_id:
        return restful.params_error('没有传入cms用户id！')
    cuser = CMSUser.query.get(cuser_id)
    if not cuser:
        return restful.params_error('没有这个cms用户存在！')
    if cuser.current_status == 1:
        cuser.current_status = 0
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error('该用户已经移入到了黑名单！')


# 取消黑名单outblacklist
@bp.route('/outblacklist/', methods=['POST'])
@login_required
@permission_requred(CMSPermission.CMSUSER)
def outblacklist():
    cuser_id = request.form.get('cuser_id')
    if not cuser_id:
        return restful.params_error('没有传入cms用户id！')
    cuser = CMSUser.query.get(cuser_id)
    if not cuser:
        return restful.params_error('没有这个cms用户存在！')
    if cuser.current_status == 0:
        cuser.current_status = 1
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error('该用户已经取消了黑名单！')


# 权限管理
@bp.route('/croles/')
@login_required
@permission_requred(CMSPermission.ALL_PERMISSION)
def croles():
    roles = CMSRole.query.all()
    content = {
        'roles': roles
    }
    return render_template('cms/cms_croles.html', **content)


# 轮播图
@bp.route('/banners/')
@login_required
def banners():
    banners = BannerModel.query.order_by(BannerModel.priority.desc()).all()
    # print(banners)
    return render_template('cms/cms_banners.html', banners=banners)


# 添加轮播图信息
@bp.route('/abanner/', methods=['POST'])
@login_required
def abanner():
    form = AddBannerForm(request.form)
    if form.validate():
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner = BannerModel(name=name, image_url=image_url, link_url=link_url, priority=priority)
        db.session.add(banner)
        db.session.commit()
        return restful.success()
    else:
        return restful.params_error(form.get_error())


# 修改轮播图
@bp.route('/ubanner/', methods=['POST'])
@login_required
def ubanner():
    form = UpdateBannerForm(request.form)
    if form.validate():
        banner_id = form.banner_id.data
        name = form.name.data
        image_url = form.image_url.data
        link_url = form.link_url.data
        priority = form.priority.data
        banner = BannerModel.query.get(banner_id)
        if banner:
            banner.name = name
            banner.image_url = image_url
            banner.link_url = link_url
            banner.priority = priority
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error('没有这个轮播图！')
    else:
        return restful.params_error(form.get_error())


# 删除轮播图
@bp.route('/dbanner/', methods=['POST'])
@login_required
def dbanner():
    banner_id = request.form.get('banner_id')
    if not banner_id:
        return restful.params_error('请传入轮播图的id！')
    banner = BannerModel.query.get(banner_id)
    if not banner:
        return restful.params_error('没有这个轮播图！')
    db.session.delete(banner)
    db.session.commit()
    return restful.success()


# 注销
@bp.route('/logout/')
@login_required
def logout():
    # session.clear()
    del session[config.CMS_USER_ID]
    return redirect(url_for('cms.login'))


@bp.route('/fpwd/', methods=['GET', 'POST'])
def fpwd():
    if request.method == 'POST':
        form = C_FoundPwdForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            cuser = CMSUser.query.filter_by(email=email).first()
            if cuser:
                cuser.password = password
                db.session.commit()
                return restful.success()
            else:
                return restful.params_error('未查询到该用户的存在！')
        else:
            return restful.params_error(form.get_error())
    return render_template('cms/cms_fpwd.html')


# 登录的类视图
class LoginView(views.MethodView):

    def get(self, message=None):
        return render_template('cms/cms_login.html', message=message)

    def post(self):
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            remember = form.remember.data
            # print(email, password, remember)
            user = CMSUser.query.filter_by(email=email).first()
            if user and user.check_password(raw_password=password):
                if user.current_status == 1:
                    session[config.CMS_USER_ID] = user.id
                    if remember:
                        session.permanent = True
                    return redirect(url_for('cms.index'))
                else:
                    return self.get(message='当前用户已被封号！')
            else:
                return self.get(message='邮箱或者密码错误')
        else:
            print(form.errors)
            message = form.get_error()
            return self.get(message)


# 修改密码
class ResetPwdView(views.MethodView):
    decorators = [login_required]

    def get(self):
        return render_template('cms/cms_resetpwd.html')

    def post(self):
        form = ResetForm(request.form)
        if form.validate():
            newpwd = form.newpwd.data
            oldpwd = form.oldpwd.data
            user = g.cms_user
            if user.check_password(oldpwd):
                user.password = newpwd
                db.session.commit()
                return restful.success()
            else:
                return restful.params_error('原密码错误')
        else:
            return restful.params_error(form.get_error())


# 修改邮箱
class ResetEmainView(views.MethodView):
    decorators = [login_required]

    def get(self):
        return render_template('cms/cms_resetemail.html')

    def post(self):
        form = ResetEmailForm(request.form)
        if form.validate():
            email = form.email.data
            user = CMSUser.query.filter_by(email=email).first()
            if not user:
                g.cms_user.email = email
                db.session.commit()
                return restful.success()
            else:
                return restful.params_error('该邮箱已存在！')
        else:
            return restful.params_error(form.get_error())


bp.add_url_rule('/login/', view_func=LoginView.as_view('login'))
bp.add_url_rule('/resetpwd/', view_func=ResetPwdView.as_view('resetpwd'))
bp.add_url_rule('/resetemail/', view_func=ResetEmainView.as_view('resetemail'))


# 个人信息
@bp.route('/profile/')
@login_required
def cms_profile():
    return render_template('cms/cms_profile.html')
